package main

import (
	"fmt"
	"net/http"
	_ "net/http"
	_ "net/http/pprof"
	"os"
	"strconv"
	"sync"
	"zhejianglab/gin-apiserver/initialize"
	"zhejianglab/gin-apiserver/model"
	gr "zhejianglab/gin-apiserver/pkg/grpc"
	"zhejianglab/gin-apiserver/pkg/logger"
	"zhejianglab/gin-apiserver/pkg/setting"
	"zhejianglab/gin-apiserver/pkg/websocket"
	v1 "zhejianglab/gin-apiserver/routers/api/v1"
)

func init() {
	// initialize logger
	if err := logger.Init(-1, "2006-01-02T15:04:05Z07:00"); err != nil {
		fmt.Errorf("failed to initialize logger: %v", err)
	}

	// load not deal job from db to cache
	SyncDBtoCache()

	// 创建保存文件的目录
	err := os.MkdirAll(setting.FileSRC, os.ModePerm)
	if err != nil {
		fmt.Errorf("failed to mkdir "+setting.FileSRC, err)
	}
}

func main() {
	// create a WaitGroup
	wg := new(sync.WaitGroup)

	// add three goroutines to `wg` WaitGroup
	wg.Add(4)

	go func() {
		logger.Log.Info("Start apiServer ...")
		router := initialize.InitRouter()
		port := fmt.Sprintf(":%s", strconv.Itoa(setting.HTTPPort))
		router.Run(port)
		wg.Done()
	}()
	go func() {
		gr.StartReIDGrpc()
		wg.Done()
	}()
	go func() {
		websocket.RunWebsocket()
		wg.Done()
	}()

	go func() {
		// open pprof server to check cpu and memory leak
		http.ListenAndServe("0.0.0.0:2020", nil)
		wg.Done()
	}()
	wg.Wait()

}

func SyncDBtoCache() {
	data, err := model.GetAllJobs()
	if err != nil {
		logger.Log.Info("syncDBtoCache failed!")
	}
	for i, v := range data {
		if v.Progress != 100 {
			fmt.Println("set db to cache", i)
			v1.PutJob(v)
		} else if v.Progress == -1 {
			model.DeleteJob(int(v.ID))
		}
	}
}
